package com.zsr.chapter05.servlet;

import com.zsr.chapter05.bean.Book;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @Author zsr
 * @Description 展示加入购物车的图书
 * @Date 2021/4/22 10:34
 */
public class CartServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        //变量cart引用用户的购物车
        List<Book> cart =null;
        //变量flag标记用户是否购买 过商品
        boolean flag= true;
        //获取用户的session
        HttpSession session = request.getSession();
        //如果session为空，flag设置为false
        if(session==null){
            flag=false;
        }else{
            //获得用户购物车
            cart=(List)session.getAttribute("cart");
            if(cart==null){
                flag=false;
            }
        }
        if(!flag){
            out.print("对不起！您还没有购买任何商品！<br/>");
        }else{
            //否则显示用户购买图书的信息
            out.print("您购买的图书有：<br/>");
            double price=0;
            for (Book book : cart) {
                String url="/javaweb_task_demo/cancelOrderServlet?id="+book.getId();
                out.print(book.getName() +"<a href='"+url+"'>取消订单</a><br/>");
            }
        }

    }
}
